package com.chenhj.service.imp;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.UUID;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chenhj.customEnum.Znx;
import com.chenhj.dao.LoanlimitsDao;
import com.chenhj.dto.Content;
import com.chenhj.dto.Req;
import com.chenhj.entity.Loanlimits;
import com.chenhj.service.LoanlimitsService;
import com.chenhj.utils.DateTimeUtil;
import com.chenhj.utils.XstreamXMLUtil;

@Service
public class LoanlimitsServiceImp implements LoanlimitsService {

	@Autowired
	private LoanlimitsDao loanlimitsDao;

	private final static String EMPTY = "";
	
	private static ResourceBundle rb = ResourceBundle.getBundle("properties/config");
	
	@Override
	public List<String> postXml(int offset, int limit, int whether, String tableName, String productId,
			String bankName) {
		List<Loanlimits> list = loanlimitsDao.queryAll(offset, limit, whether, tableName);
		List<String> resultList = new ArrayList<String>();

		for (Loanlimits loanlimits : list) {
			Content content = new Content();

			// 获取信息内容
			String text = getText(loanlimits, productId, bankName);
			if (text == null) {
				continue;
			}

			content.setText(text);

			content.setTitle("金融街预授信信息");
			content.setMsgtype("pm");
			content.setUrl(EMPTY);
			content.setSignname(EMPTY);
			content.setAreacode(EMPTY);
			content.setPushdesc("1");
			content.setData(EMPTY);
			content.setBiztype("syfw001");
			content.setSubbiztype("10001");
			content.setUsetemplate("0");
			content.setRecipients(loanlimits.getDjxh());
			content.setNsrdzdah(loanlimits.getDjxh());
			content.setSendtime(EMPTY);

			String contentXml = XstreamXMLUtil.objToXml(content);
			contentXml = Base64.encodeBase64String(contentXml.getBytes());

			// 拼接req报文
			Req req = new Req();
			req.setId("UUID");
			req.setChannel("SMSCenter");
			req.setAct("sendmessage");
			req.setBody(contentXml);

			String xmlToDzswj = XstreamXMLUtil.objToXml(req);
			resultList.add(xmlToDzswj);
		}
		return resultList;
	}

	@Override
	public void addFailuredLoanlimits(String reqXml, String tableName) {
		String failed = "failed";
		Req req = XstreamXMLUtil.xmlToBean(reqXml, Req.class);
		String body = req.getBody();
		String contentXml = new String(Base64.decodeBase64(body));
		Content content = XstreamXMLUtil.xmlToBean(contentXml, Content.class);
		String djxh = content.getRecipients();
		Loanlimits loanlimits = new Loanlimits();
		loanlimits.setDjxh(djxh);
		if (Znx.JSYH.getTableName().equals(tableName)) {
			loanlimits.setJsyh(failed);
		} else if (Znx.ZGYH.getTableName().equals(tableName)) {
			loanlimits.setZgyh(failed);
		} else if (Znx.ZHASYH.getTableName().equals(tableName)) {
			loanlimits.setZhasyh(failed);
		} else if (Znx.ZSYH.getTableName().equals(tableName)) {
			loanlimits.setZsyh(failed);
		}
		loanlimitsDao.addFailuredLoanlimits(loanlimits);
	}

	@Override
	public int getCount(String tableName) {
		return loanlimitsDao.getCount(tableName);
	}

	// 提示消息内容
	public String getText(Loanlimits loanlimits, String productId, String bankName) {

		String url = getUrl(loanlimits, productId);
		String loanLimit = null;
		if ("3".equals(productId)) {
			loanLimit = loanlimits.getJsyh();
		} else if ("18".equals(productId)) {
			loanLimit = loanlimits.getZgyh();
		} else if ("29".equals(productId)) {
			loanLimit = loanlimits.getZhasyh();
		}

		String[] section = loanLimit.split("-");
		Integer min = (int) Double.parseDouble(section[0]);
		Integer max = (int) Double.parseDouble(section[1]);
		loanLimit = (min / 10000) + "~" + (max / 10000) + "万元";
		// System.out.println("nsrmc==="+loanlimits.getNsrmc()+"--"+loanLimit);
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("尊敬的纳税人: <br/>");
		stringBuffer.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
		stringBuffer.append("江苏国税税银互动服务金融街上线以来，联合多家银行累计为20000余户纳税人提供了授信服务，有效的帮助了小微企业的发展，解决了小微企业融资难融资贵的问题。<br/>");
		stringBuffer.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
		stringBuffer.append("根据您目前的纳税信用数据综合评判，您已满足<strong>" + bankName + "</strong>的授信产品申请条件，预计授信额度为<strong>"
				+ loanLimit + "</strong>（具体授信额度以银行审批为准）。假如您有融资需求，<a href ='" + url
				+ "'><font color=blue>可以点击此链接进行申请。</font></a><br/>");
		stringBuffer.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
		stringBuffer.append("<strong>说明:</strong>申请无需支付任何费用，授信获批后银行仅收取您使用款项所对应的利息，假如金融机构有向您收取除利息之外的任何费用，请拨打12366进行投诉!");
		return stringBuffer.toString();
	}

	// 提示消息内容
	public String getText2(Loanlimits loanlimits, String productId, String bankName) {

		String url = getUrl(loanlimits, productId);
		String loanLimit = null;
		if ("3".equals(productId)) {
			loanLimit = loanlimits.getJsyh();
		} else if ("18".equals(productId)) {
			loanLimit = loanlimits.getZgyh();
		} else if ("29".equals(productId)) {
			loanLimit = loanlimits.getZhasyh();
		} else {
			loanLimit = loanlimits.getZsyh();
			url = "可在<a href ='https://directbank.czbank.com/APPINSPECT/index.jsp'><font color=blue>银行官网页面</font></a>左侧树的：金融服务分类  --> 贷款业务 --> 小企业贷款e申请,进行申请。(浏览器：建议IE8及以上版本。)<br/>";
		}

		String[] section = loanLimit.split("-");
		Integer min = (int) Double.parseDouble(section[0]);
		Integer max = (int) Double.parseDouble(section[1]);
		loanLimit = (min / 10000) + "~" + (max / 10000) + "万元";
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("尊敬的纳税人: <br/>");
		stringBuffer.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
		stringBuffer.append("江苏国税税银互动服务金融街上线以来，联合多家银行累计为20000余户纳税人提供了授信服务，有效的帮助了小微企业的发展，解决了小微企业融资难融资贵的问题。<br/>");
		stringBuffer.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
		stringBuffer.append("根据您目前的纳税信用数据综合评判，您已满足<strong>" + bankName + "</strong>的授信产品申请条件，预计授信额度为<strong>"
				+ loanLimit + "</strong>（具体授信额度以银行审批为准）。假如您有融资需求，");
		stringBuffer.append(url);
		stringBuffer.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
		stringBuffer.append("<strong>说明:</strong>申请无需支付任何费用，授信获批后银行仅收取您使用款项所对应的利息，假如金融机构有向您收取除利息之外的任何费用，请拨打12366进行投诉!");
		return stringBuffer.toString();
	}

	public String getUrl(Loanlimits loanlimits, String productId) {
		String url = rb.getString("url_sz");
		String message = getParams(loanlimits, productId);
		return url + message;
	}

	public String getParams(Loanlimits loanlimits, String productId) {
		String params = null;
		String time = DateTimeUtil.formatDate3(new Date());
		String lpbm = UUID.randomUUID().toString();
		Map<String, String> dataMap = new HashMap<String, String>();
		dataMap.put("nsrsbh", loanlimits.getNsrsbh());
		dataMap.put("userid", loanlimits.getDjxh());
		dataMap.put("nsrSwjgDM", loanlimits.getNsrswjgdm());
		dataMap.put("nsrdzdah", loanlimits.getNsrdzdah());
		dataMap.put("nsrmc", loanlimits.getNsrmc());
		dataMap.put("time", time);
		dataMap.put("mobile", loanlimits.getMobile());
		dataMap.put("tokenLpbm", lpbm);
		dataMap.put("productId", productId);
		dataMap.put("areaCode", getAreaCode(loanlimits.getNsrswjgdm()));
		params = this.encryptParams(dataMap);
		return params;
	}

	public String getAreaCode(String nsrSwjgDM) {
		String areaCode = "000000";
		areaCode = nsrSwjgDM.substring(1, 5);
		if ("3216".equals(areaCode) || "3217".equals(areaCode)) {
			areaCode = "3205";
		} else if ("3215".equals(areaCode)) {
			areaCode = "3201";
		}
		areaCode = areaCode + "00";
		return areaCode;
	}

	public String encryptParams(Map<String, String> dataMap) {
		String token = dataMap.get("tokenLpbm");
		String data = "{\"lpbm\":\"" + token + "\"}";
		dataMap.remove("tokenLpbm");
		// 生成json字符�?
		String finance = this.spliceMessage(dataMap);
		String body = "{\"data\":" + data + ",\"finance\":" + finance + "}";
		String sendMsg = null;
		try {
			sendMsg = Base64.encodeBase64String(body.getBytes("UTF-8"));
			sendMsg = URLEncoder.encode(sendMsg, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return sendMsg;
	}

	// 生成报文
	public String spliceMessage(Map<String, String> dataMap) {
		String finance = "{";
		for (Map.Entry<String, String> entry : dataMap.entrySet()) {
			finance = finance + "\"" + entry.getKey().toUpperCase() + "\":\"" + entry.getValue() + "\",";
		}
		finance = finance.substring(0, finance.length() - 1) + "}";
		return finance;
	}

}
